<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\FeishuMini\ProgrammingEnum;
use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Common\CityResidencePriceModel;
use App\Models\Common\MapNationalCommunityModel;
use App\Models\Common\MapNationalIndustrialParkModel;
use App\Models\Common\MapNationalStreetModel;
use App\Models\Common\MapNationalUniversitiesModel;
use App\Models\Common\MapTownshipPlanAreaModel;
use App\Models\OpenShop\Common\SiteLocationMallModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use App\Models\Wanggui\CustomerDepartmentTaskModel;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Redis;
use Overtrue\Pinyin\Pinyin;

class WangguiSyncKfShop extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'wanggui:sync-kf-shop-count';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '网规点位夸父门店数量同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        GuanyuanDataService::setTimeOut(30);
        try {
            $kfShop = GuanyuanDataService::newShopList();
        } catch (\Exception $exception) {
            $kfShop = [];
        }
        $shopDot  = [];
        $townList = [];
        foreach ($kfShop as $shop) {
            if (!$shop['门店经度'] || !$shop['门店纬度']) {
                continue;
            }
            $this->info($shop['门店名称']);
            $townList[] = Cache::remember('tiger:openShop:wanggui:shop:town:' . $shop['门店经度'] . $shop['门店纬度'], 96400, function () use ($shop) {
                $this->info('2  ' . date('Ymd His'));
                $key     = WangGuiCityByPower::getRandomAmapKey();
                $areaRes = Http::withHeaders(['Content-Type' => 'application/json; charset=utf-8'])
                    ->get(sprintf(config('area.amapGetDistrictByLatLng'), $shop['门店经度'], $shop['门店纬度'], $key))
                    ->json();
                return $areaRes['regeocode']['addressComponent']['township'] ?? '';
            });
            $shopDot[]  = [
                $shop['门店经度'],
                $shop['门店纬度']
            ];
            Redis::geoAdd('tiger:wanggui:dot', $shop['门店经度'], $shop['门店纬度'], 'KFZC' . (ProgrammingEnum::KF_SHOP_STATUS_REVERSE_MAPPING[$shop['状态']] ?? 0) . $shop['铺位号']);
        }

        $num = 0;
        MapNationalIndustrialParkModel::query()
            ->chunk(1000, function ($arr) use (&$num) {
                foreach ($arr as $value) {
                    $count   = 0;
                    $dotList = Redis::georadius('tiger:wanggui:dot', $value->lon, $value->lat, '300', 'm');
                    foreach ($dotList as $dot) {
                        if (mb_strpos($dot, 'KFZC') === 0 && in_array(substr($dot, 4, 1), [ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, ProgrammingEnum::KF_SHOP_STATUS_PREPARE])) {
                            $count++;
                        }
                    }
                    $value->shopNum = $count;
                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->save();
                }
                $this->info(1000 * $num);
                $num++;
            });

        // 清空任务入驻状态
        CustomerDepartmentTaskModel::query()
            ->update([
                'settle' => CustomerDepartmentTaskModel::SETTLE_STATUS_OFF
            ]);

        SiteLocationMallModel::query()
            ->where('grade', '>', 0)
            ->chunk(1000, function ($arr) use (&$num) {
                $settleArr = [];
                foreach ($arr as $value) {
                    $count   = 0;
                    $dotList = Redis::georadius('tiger:wanggui:dot', $value->lng, $value->lat, '200', 'm');

                    // 判断是否已有选址和商场匹配
                    $isSetMall = OpenShopSiteLocationModel::query()->where('source', OpenShopSiteLocationModel::SOURCE_OPEN_SHOP)->where('siteStatus', OpenShopSiteLocationModel::SITE_STATUS_4)->where('mallId', $value->mallId)->exists();
                    if ($isSetMall) {
                        $count = 1;
                    } else {
                        foreach ($dotList as $dot) {
                            if (mb_strpos($dot, 'KFZC') === 0 && in_array(substr($dot, 4, 1), [ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, ProgrammingEnum::KF_SHOP_STATUS_PREPARE])) {
                                $count++;
                            }
                        }
                    }
                    $value->shopNum = $count;
                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                        $settleArr[]   = $value->wgNumber;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->save();
                }
                CustomerDepartmentTaskModel::query()
                    ->whereIn('wgNumber', $settleArr)
                    ->update([
                        'settle'       => CustomerDepartmentTaskModel::SETTLE_STATUS_OK,
                        'manageStatus' => CustomerDepartmentTaskModel::MANAGE_STATUS_COMPLETE,
                    ]);
                $this->info(1000 * $num);
                $num++;
            });

        MapTownshipPlanAreaModel::query()
            ->chunk(1000, function ($arr) use (&$num, $townList) {
                foreach ($arr as $value) {
                    $count = 0;
                    foreach ($townList as $dot) {
                        if ($dot == $value->area) {
                            $count++;
                        }
                    }
                    $value->shopNum = $count;
                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->save();
                }
                $this->info(1000 * $num);
                $num++;
            });

        MapNationalUniversitiesModel::query()
            ->chunk(1000, function ($arr) use (&$num, $shopDot) {
                foreach ($arr as $value) {
                    $count = 0;
                    if ($value->boundary) {
                        $polygon = new \League\Geotools\Polygon\Polygon(json_decode($value->boundary, true));
                        $polygon->setPrecision(5);
                        foreach ($shopDot as $dot) {
                            $res = $polygon->pointInPolygon(new \League\Geotools\Coordinate\Coordinate([$dot[0], $dot[1]])); // true
                            if ($res) {
                                $count++;
                            }
                        }
                    } else {
                        $dotList = Redis::georadius('tiger:wanggui:dot', $value->lon, $value->lat, '300', 'm');
                        foreach ($dotList as $dot) {
                            if (mb_strpos($dot, 'KFZC') === 0 && in_array(substr($dot, 4, 1), [ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, ProgrammingEnum::KF_SHOP_STATUS_PREPARE])) {
                                $count++;
                            }
                        }
                    }
                    $value->shopNum = $count;
                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->save();
                }
                $this->info(1000 * $num);
                $num++;
            });

        MapNationalStreetModel::query()
            ->chunk(1000, function ($arr) use (&$num, $shopDot) {
                foreach ($arr as $value) {
                    $count = 0;
                    if ($value->boundary) {
                        $polygon = new \League\Geotools\Polygon\Polygon(json_decode($value->boundary, true));
                        $polygon->setPrecision(5);
                        foreach ($shopDot as $dot) {
                            $res = $polygon->pointInPolygon(new \League\Geotools\Coordinate\Coordinate([$dot[0], $dot[1]])); // true
                            if ($res) {
                                $count++;
                            }
                        }
                    } else {
                        $dotList = Redis::georadius('tiger:wanggui:dot', $value->lng, $value->lat, '300', 'm');
                        foreach ($dotList as $dot) {
                            if (mb_strpos($dot, 'KFZC') === 0 && in_array(substr($dot, 4, 1), [ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, ProgrammingEnum::KF_SHOP_STATUS_PREPARE])) {
                                $count++;
                            }
                        }
                    }

                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->shopNum = $count;
                    $value->save();
                }
                $this->info(1000 * $num);
                $num++;
            });

        MapNationalCommunityModel::query()
            ->chunk(1000, function ($arr) use (&$num, $shopDot) {
                foreach ($arr as $value) {
                    $count = 0;
                    if ($value->boundary) {
                        $polygon = new \League\Geotools\Polygon\Polygon(json_decode($value->boundary, true));
                        $polygon->setPrecision(5);
                        foreach ($shopDot as $dot) {
                            $res = $polygon->pointInPolygon(new \League\Geotools\Coordinate\Coordinate([$dot[0], $dot[1]])); // true
                            if ($res) {
                                $count++;
                            }
                        }
                    } else {
                        $dotList = Redis::georadius('tiger:wanggui:dot', $value->lng, $value->lat, '300', 'm');
                        foreach ($dotList as $dot) {
                            if (mb_strpos($dot, 'KFZC') === 0 && in_array(substr($dot, 4, 1), [ProgrammingEnum::KF_SHOP_STATUS_BUSINESS, ProgrammingEnum::KF_SHOP_STATUS_PREPARE])) {
                                $count++;
                            }
                        }
                    }

                    if ($count > 0) {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OK;
                    } else {
                        $value->settle = ProgrammingEnum::SETTLE_STATUS_OFF;
                    }
                    $value->shopNum = $count;
                    $value->save();
                }
                $this->info(1000 * $num);
                $num++;
            });
    }
}
